package com.tiny.work.segement;

import java.util.ArrayList;
import java.util.List;

public class ExJoin extends Thread {
    public static List<String> list = new ArrayList<>();
    Thread thread;

    public ExJoin(){

    }

    public ExJoin(Thread thread){
        this.thread  = thread;
    }

    @Override
    public void run() {
        try {
            if (thread != null){
//                try{
//
//                    Thread.sleep(1000);
//
//                } catch (Exception e) {
//
//                }

                thread.join();
            }
            synchronized (list) {
                list.add(Thread.currentThread().getName());
            }
//            System.out.println(Thread.currentThread().getName()+"  is running");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void test(){
        Thread threadA = new ExJoin();
        threadA.setName("A");
        Thread threadB = new ExJoin(threadA);
        threadB.setName("B");
        Thread threadC = new ExJoin(threadB);
        threadC.setName("C");
        Thread threadD =  new ExJoin(threadC);
        threadD.setName("D");

        threadA.start();
        threadB.start();
        threadC.start();
        threadD.start();
    }


    public static void main(String[] args) throws InterruptedException {
        for (int i=0; i< 10;i++){
            test();
        }
        for (int i = 0; i < list.size(); i += 4) {
            if (!list.get(i).equals("A")) System.err.print("error");
            if (!list.get(i+1).equals("B")) System.err.print("error");
            if (!list.get(i+2).equals("C")) System.err.print("error");
            if (!list.get(i+3).equals("D")) System.err.print("error");
        }
    }
}
